package com.ajk.server.service.impl;
import java.util.Collections;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ajk.message.model.BaseModel;
import com.ajk.server.dao.FriendPartientEventExtMapper;
import com.ajk.server.dao.FriendPatientEventDayMapper;
import com.ajk.server.dao.FriendPatientEventMapper;
import com.ajk.server.exception.AjkException;
import com.ajk.server.exception.ErrorConstant;
import com.ajk.server.model.FriendPartientEventExt;
import com.ajk.server.model.FriendPatientEvent;
import com.ajk.server.model.FriendPatientEventDay;
import com.ajk.server.model.query.FriendPatientEventQuery;
import com.ajk.server.service.FriendPatientEventDayService;
import com.ajk.server.service.FriendPatientEventService;
import com.google.gson.JsonObject;

/**
 * 亲友健康数据  <br>
 * t_friend_patient_event <br>
 * v1.0 2016-05-01
 */
@Service
public class FriendPatientEventServiceImpl implements FriendPatientEventService {

	private static final Logger logger = LoggerFactory.getLogger(FriendPatientEventServiceImpl.class);

	@Autowired
	private FriendPatientEventMapper friendPatientEventMapper;

	@Autowired
	FriendPartientEventExtMapper friendPartientEventExtMapper;

	@Autowired
	FriendPatientEventDayService friendPatientEventDayService;
	
	@Autowired
	FriendPatientEventDayMapper friendPatientEventDayMapper;
	
	@Autowired
	RedisTemplate<String, Object> template;
	/**
	 *根据ID删除 亲友健康数据
	 */
	@Override
	public Integer deleteFriendPatientEventById(Integer id){
		return friendPatientEventMapper.deleteById(id);
	}

	/**
	 *新增 亲友健康数据
	 */
	@Override
	@Transactional
	public Integer batchInsertFriendPatientEvent(List<? extends FriendPatientEvent> friendPatientEvents){
		Integer count = friendPatientEventMapper.batchInsert(friendPatientEvents);
		return count;
	}
	/**
	 *新增 亲友健康数据
	 */
	@Override
	@Transactional
	public Integer insertFriendPatientEvent(FriendPatientEventDay patientEvent){
		Integer userId = patientEvent.getUserId();
		Integer friendId = patientEvent.getFriendId();
		String content = patientEvent.getContent();
		String uuid = patientEvent.getUuid();
		Integer categoryId = patientEvent.getCategoryId();

		FriendPatientEvent pe = friendPatientEventMapper.findByUuidAndFriendId(uuid,friendId);

		if(pe!=null){
			AjkException exception = new AjkException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"uuid("+uuid+")，friendId("+friendId+")对应的数据已经存在，不能添加");
			logger.info("添加健康数据",exception);
			throw exception;
		}

		friendPatientEventMapper.insert(patientEvent);
		Integer patientEventId = patientEvent.getId();

		FriendPartientEventExt ext = new FriendPartientEventExt();
		ext.setParentId(patientEventId);
		ext.setCategoryId(categoryId);
		ext.setFriendId(friendId);
		JsonObject contentJson = BaseModel.gson.fromJson(content, JsonObject.class);
		switch (categoryId) {
		case 1:
			Double bloodOxygen = contentJson.get("bloodOxygen").getAsDouble();
			ext.setBloodOxygen(bloodOxygen);
			break;
		case 2:
			Double systolicPressure = contentJson.get("systolicPressure").getAsDouble();
			Double diastolicPressure = contentJson.get("diastolicPressure").getAsDouble();
			ext.setSystolicPressure(systolicPressure);
			ext.setDiastolicPressure(diastolicPressure);
			break;
		case 3:
			Integer timeBlockId = contentJson.get("timeBlockId").getAsInt();
			Double bloodSugar = contentJson.get("bloodSugar").getAsDouble();
			ext.setBloodSugar(bloodSugar);
			ext.setTimeBlockId(timeBlockId);
			break;
		case 4:
			Double temperature = contentJson.get("temperature").getAsDouble();
			ext.setTemperature(temperature);
			break;
		case 5:
			Integer heartRate = contentJson.get("heartRate").getAsInt();
			ext.setHeartRate(heartRate);
			break;
		case 6:
			Integer bodyAge = contentJson.get("bodyAge").getAsInt();
			ext.setBodyAge(bodyAge);
			break;
		default:
			AjkException exception = new AjkException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"categoryId 超出范围");
			logger.info("添加健康数据",exception);
			throw exception;
		}
		friendPartientEventExtMapper.insert(ext);
		
		//按照categoryId和actionTime查询当天是否已经有数据了
		
		//放入patient_event_day
		patientEvent.setPatientEventId(patientEventId);
		patientEvent.setId(null);
		friendPatientEventDayService.insertFriendPatientEventDay(patientEvent);
		
		return patientEventId;
	}

	/**
	 *更新 亲友健康数据
	 */
	@Override
	@Transactional
	public Integer updateFriendPatientEvent(FriendPatientEventDay patientEvent){

		Integer userId = patientEvent.getUserId();
		Integer friendId = patientEvent.getFriendId();
		Integer id = patientEvent.getId();
		FriendPatientEventDay db = friendPatientEventDayMapper.findById(id);
		if(db==null){
			AjkException exception = new AjkException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"修改的数据不存在");
			logger.info("添加健康数据",exception);
			throw exception;
		}

		if(db.getUserId().intValue()!=userId.intValue()){
			AjkException exception = new AjkException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"无权限修改比人的健康数据");
			logger.info("添加健康数据",exception);
			throw exception;
		}
		
		Integer patientEventId = db.getPatientEventId();
		patientEvent.setId(patientEventId);
		friendPatientEventMapper.update(patientEvent);
		patientEvent.setId(id);
		FriendPartientEventExt ext = friendPartientEventExtMapper.findByParentId(patientEventId);
		boolean isExists = true;
		if(ext == null){
			ext = new FriendPartientEventExt();
			ext.setFriendId(friendId);
			isExists = false;
		}
		Integer categoryId = db.getCategoryId();
		String content = patientEvent.getContent();
		if(StringUtils.isEmpty(content)){
			content = db.getContent();
		}
		ext.setParentId(patientEventId);
		ext.setCategoryId(categoryId);
		JsonObject contentJson = BaseModel.gson.fromJson(content, JsonObject.class);
		switch (categoryId) {
		case 1:
			Double bloodOxygen = contentJson.get("bloodOxygen").getAsDouble();
			ext.setBloodOxygen(bloodOxygen);
			break;
		case 2:
			Double systolicPressure = contentJson.get("systolicPressure").getAsDouble();
			Double diastolicPressure = contentJson.get("diastolicPressure").getAsDouble();
			ext.setSystolicPressure(systolicPressure);
			ext.setDiastolicPressure(diastolicPressure);
			break;
		case 3:
			Integer timeBlockId = contentJson.get("timeBlockId").getAsInt();
			Double bloodSugar = contentJson.get("bloodSugar").getAsDouble();
			ext.setBloodSugar(bloodSugar);
			ext.setTimeBlockId(timeBlockId);
			break;
		case 4:
			Double temperature = contentJson.get("temperature").getAsDouble();
			ext.setTemperature(temperature);
			break;
		case 5:
			Integer heartRate = contentJson.get("heartRate").getAsInt();
			ext.setHeartRate(heartRate);
			break;
		case 6:
			Integer bodyAge = contentJson.get("bodyAge").getAsInt();
			ext.setBodyAge(bodyAge);
			break;
		default:
			AjkException exception = new AjkException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"categoryId 超出范围");
			logger.info("添加健康数据",exception);
			throw exception;
		}
		if(isExists){
			friendPartientEventExtMapper.update(ext);
		}else{
			friendPartientEventExtMapper.insert(ext);
		}
		
		
		patientEvent.setPatientEventId(patientEventId);
		patientEvent.setId(id);
		friendPatientEventDayService.updateFriendPatientEventDay(patientEvent);
		
		return id;
	
	}

	/**
	 *根据ID查询 亲友健康数据
	 */
	public FriendPatientEvent findFriendPatientEventById(Integer id){
		FriendPatientEvent result = friendPatientEventMapper.findById(id);
		if(result!=null){
			result.dealWith();
		}
		return result;
	}

	/**
	 *通过query 查询 亲友健康数据
	 */
	public List<FriendPatientEvent> findFriendPatientEventByQuery(FriendPatientEventQuery query){
		query.dealWith();
		List<FriendPatientEvent> result = friendPatientEventMapper.findByQuery(query);
		if(CollectionUtils.isNotEmpty(result)) {
			Collections.sort(result);
			for (FriendPatientEvent friendPatientEvent : result) {
				friendPatientEvent.dealWith();
			}
		}
		return result;
	}	

	/**
	 *通过query count总条数
	 */
	public Integer countFriendPatientEventByQuery(FriendPatientEventQuery query){
		query.dealWith();
		Integer result = friendPatientEventMapper.countByQuery(query);
		return result;
	}

	/**
	 * 通过ids查询
	 */
	public List<FriendPatientEvent> findFriendPatientEventByIds(List<Integer> ids){
		List<FriendPatientEvent> result = friendPatientEventMapper.findByIds(ids);
		if(CollectionUtils.isNotEmpty(result)) {
			for (FriendPatientEvent friendPatientEvent : result) {
				friendPatientEvent.dealWith();
			}
		}
		return result;
	}

}	